package mspbots.data.tl.prod.autotask.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.tl.base.AbstractBaseServiceImpl;
import mspbots.data.tl.entity.ResultEntity;
import mspbots.data.tl.prod.autotask.mapper.TaskAutotaskSurveyResultMapper;
import mspbots.data.tl.prod.autotask.model.TaskAutotaskSurveyResult;
import mspbots.data.tl.prod.autotask.service.TaskAutotaskSurveyResultService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Log4j2
@RequiredArgsConstructor
@DS("master")
public class TaskAutotaskSurveyResultServiceImpl extends AbstractBaseServiceImpl<TaskAutotaskSurveyResultMapper, TaskAutotaskSurveyResult>
        implements TaskAutotaskSurveyResultService {

    private final TaskAutotaskSurveyResultMapper autotaskSurveyResultMapper;

    @Override
    public void sync(ResultEntity content) {
        log.debug("Auto task surveyResult receiver content {}", content);
        JsonNode entity = content.getEntity();
        TaskAutotaskSurveyResult data = TaskAutotaskSurveyResult.builder()
                .surveyResultId(super.getLongValue(entity.get("id")))
                .surveyId(super.getIntegerValue(entity.get("surveyID")))
                .contactId(super.getIntegerValue(entity.get("contactID")))
                .ticketId(super.getIntegerValue(entity.get("ticketID")))
                .surveyRating(super.getStringValue(entity.get("surveyRating")))
                .contactRating(super.getStringValue(entity.get("contactRating")))
                .resourceRating(super.getStringValue(entity.get("resourceRating")))
                .companyRating(super.getStringValue(entity.get("companyRating")))
                .sendDate(super.getDateTimeValue(entity.get("sendDate")))
                .completeDate(super.getDateTimeValue(entity.get("completeDate")))
                .syncTime(LocalDateTime.now())
                .build();
        data.setTenantCode(content.getTenantId());

        TaskAutotaskSurveyResult dbData = super.baseMapper.selectOne(Wrappers.<TaskAutotaskSurveyResult>lambdaQuery()
                .eq(TaskAutotaskSurveyResult::getTenantCode, data.getTenantCode())
                .eq(TaskAutotaskSurveyResult::getSurveyResultId, data.getSurveyResultId())
                .last("limit 1"));
        if (ObjectUtils.isEmpty(dbData)) {
            super.baseMapper.insert(data);
        } else {
            data.setId(dbData.getId());
            super.baseMapper.updateById(data);

        }
    }
}